package br.edu.unirn.controle;

import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.swing.text.TableView;

import org.primefaces.component.tabview.TabView;

import br.edu.unirn.dao.CategoriaDAO;
import br.edu.unirn.dao.GenericDAO;
import br.edu.unirn.dao.IGenericDAO;
import br.edu.unirn.dao.PersistDB;
import br.edu.unirn.dominio.Categoria;

public class AbstractController{

	protected IGenericDAO dao;
	private TabView tabCrud = new TabView();
	protected PersistDB obj;
	
	public void addInfo(String msg){
		FacesMessage fm = new FacesMessage(msg);
		FacesContext.getCurrentInstance().addMessage(null, fm);
	}
	
	
	public List<PersistDB> getListaCompleta(){
		try{
			return dao.findAll();	
		}finally{
			dao.close();
		}
	}

	public String deletar(PersistDB obj){
		
		try{
			dao.delete(dao.castGeneric(obj));
		}finally{
			dao.close();
		}
		addInfo("apagada com sucesso.");
		return null;
	}
	
	public String selecionar(PersistDB obj){
		this.obj = obj;
		tabCrud.setActiveIndex(1);
		return null;
	}
	
	public String salvar(){
			try{
				
				if(obj.getId()==0){
					dao.create(dao.castGeneric(obj));
					dao.getEm().refresh(obj);
					
				}else{
					
					dao.update(dao.castGeneric(obj));
				}
				
				try {
					obj = obj.getClass().newInstance();
				} catch (InstantiationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}finally{
				dao.close();
			}
			
			addInfo("salva com sucesso.");
			tabCrud.setActiveIndex(0);
			getListaCompleta();
			return null;
		}


	public IGenericDAO<PersistDB> getDao() {
		return dao;
	}


	public void setDao(IGenericDAO<PersistDB> dao) {
		this.dao = dao;
	}


	public TabView getTabCrud() {
		return tabCrud;
	}


	public void setTabCrud(TabView tabCrud) {
		this.tabCrud = tabCrud;
	}


	public PersistDB getObj() {
		return obj;
	}


	public void setObj(PersistDB obj) {
		this.obj = obj;
	}
		

	
}
